<?php
/**
 * FastApp.
 * 9/21/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Game\Api\Service;

use App\Fastapp\Api\Service\BaseService;
use App\Game\Model\GameAccount;
use App\Game\Model\GameBet;
use App\Game\Model\GameProfit;
use App\Game\Model\GameUserRegister;
use Carbon\Carbon;

class TeamService extends BaseService
{
    public function level1(): array
    {
        $uid = get_uid();
        $paginate = GameAccount::query()->with(['account:gene_id,username,no,created_at,last_at', 'level:user_id,level', 'recharge', 'bet', 'children'])
            ->where(['parent_id' => $uid])->simplePaginate();
        $list = [];
        foreach ($paginate->items() as $item) {
            $list[] = [
                'user_id' => $item->user_id,
                'username' => $item->account->username,
                'no' => $item->account->no,
                'created_at' => $item->account->created_at,
                'last_at' => $item->account->last_at,
                'level' => $item->level->level ?? 0,
                'recharge' => $item->recharge->amount ?: 0,
                'bet' => $item->bet->amount ?: 0,
                'children' => $item->children->num ?: 0,
            ];
        }
        return ['list' => $list];
    }

    public function level2(): array
    {
        $uid = get_uid();
        $pids = GameAccount::query()->where(['parent_id' => $uid])->pluck('user_id');
        $paginate = GameAccount::query()->with(['account:gene_id,username,no,created_at,last_at', 'level:user_id,level', 'recharge', 'bet', 'children'])->whereIn('parent_id', $pids)->simplePaginate();
        $list = [];
        foreach ($paginate->items() as $item) {
            $list[] = [
                'user_id' => $item->user_id,
                'username' => $item->account->username,
                'no' => $item->account->no,
                'created_at' => $item->account->created_at,
                'last_at' => $item->account->last_at,
                'level' => $item->level->level,
                'recharge' => $item->recharge->amount,
                'bet' => $item->bet->amount,
                'children' => $item->children->num,
            ];
        }
        return ['list' => $list];
    }

    public function statistics(array $param): array
    {
        $uid = get_uid();
        $account_type = get_user_cache('type', $uid);
        $data['total_profit'] = GameProfit::query()->where(['user_id' => $uid])->sum('amount');
        $data['pending_profit'] = '0.00';
        $k = 'game:bcu:' . $account_type;
        $date = redis()->get($k);
        if (!$date) return $data;
        $setting = api_cache()->getAppSetting($account_type);
        $start_at = $date . ' 00:00:00';
        $end_at = Carbon::now()->toDateString() . ' 00:00:00';

        $uids1 = GameAccount::query()->where(['parent_id' => $uid])->pluck('user_id')->toArray();
        $uids2 = GameAccount::query()->whereIn('parent_id', $uids1)->pluck('user_id')->toArray();
        $query = GameBet::query()->whereBetween('created_at', [$start_at, $end_at]);
        $amount1 = $query->whereIn('user_id', $uids1)->sum('amount');
        $amount2 = $query->whereIn('user_id', $uids2)->sum('amount');

        if (bccomp($amount1, $setting['working_bet_amount']) == -1) {
            $profit1 = bcmul($amount1, bcdiv($setting['working_bet_0_rate'], '100', 4), 2);
        } else {
            $profit1 = bcmul($amount1, bcdiv($setting['working_bet_1_rate'], '100', 4), 2);
        }

        if (bccomp($amount2, $setting['working_bet_amount']) == -1) {
            $profit2 = bcmul($amount2, bcdiv($setting['working_bet_0_rate'], '100', 4), 2);
        } else {
            $profit2 = bcmul($amount2, bcdiv($setting['working_bet_2_rate'], '100', 4), 2);
        }
        $data['pending_profit'] = bcadd($profit1, $profit2, 2);
        $data['level1_num'] = count($uids1);
        $data['level2_num'] = count($uids2);
        $data['total_level_num'] = $data['level1_num'] + $data['level2_num'];
        $data['total_bet'] = bcadd($amount1, $amount2, 2);
        $data['bet1'] = $amount1;
        $data['bet2'] = $amount2;
        $data['profit1'] = $profit1;
        $data['profit2'] = $profit2;
        return $data;
    }

    public function bet(array $param): array
    {
        $uid = get_uid();
        $query = GameBet::query()
            ->select(['id', 'user_id', 'game_id', 'platform', 'amount', 'payout', 'created_at'])
            ->with(['game:id,name,icon,cover', 'account:gene_id,username'])
            ->orderByDesc('id');
        if (empty($param['user_id'])) {
            $l1 = GameAccount::query()->where(['parent_id' => $uid])->pluck('user_id')->toArray();
            $l2 = GameAccount::query()->whereIn('parent_id', $l1)->pluck('user_id')->toArray();
            $query->whereIn('user_id', array_merge($l2, $l1, [$uid]));
        } else $query->where(['user_id' => $param['user_id']]);
        if (!empty($param['start_at'])) $query->whereBetween('created_at', [$param['start_at'] . ' 00:00:00', Carbon::createFromFormat('Y-m-d', $param['end_at'])->addDay()->toDateString() . ' 00:00:00']);
        $paginate = $query->simplePaginate();
        return ['list' => $paginate->items()];
    }

    public function register(array $data): array
    {
        $uid = get_uid();
        $service = new \App\Fastapp\Api\Service\Account\AccountService();
        $res = $service->registerByUsername($data);
        GameUserRegister::query()->create(['user_id' => $res['user_id'], 'parent_id' => $uid, 'date' => date('Y-m-d')]);
        return $res;
    }
}